//作者：刘婷婷
const express = require("express");
var router = express.Router();
const db = require("../model/db");

//删除文章
router.delete("/:id", async (req, res) => {
    await db.Article.deleteOne({
        _id: req.params.id,//类型转换
    })
    res.send(true);
})


//添加文章
router.post("/", async (req, res) => {
    const data = await db.Article.create(req.body);
    res.send(data);
})
//修改文章
router.put("/:id", async (req, res) => {
    await db.Article.updateOne({//条件对象
        _id: req.params.id
    }, req.body)
    res.send(true);
})


// 查询文章

// 分页查询所有文章
router.get("/", async (req, res) => {
    if (!req.query.field) {
        //默认为id序
        req.query.field = "_id";
    }
    if (!req.query.sort) {
        //默认为升序排列
        req.query.sort = "asc";
    }
    //有值的时候
    let value = req.query.field;//得到属性值
    if (req.query.sort === "desc") {
        //如果为降序 拼接一个减号 
    }
    if (!req.query.page) {
        //默认为 1 页
        req.query.page = 1;
    }
    if (!req.query.limit) {
        //默认每页显示 10 条
        req.query.limit = 10;
    }
    let condition = {};
    if (req.query.key) {
        const exp = new RegExp(req.query.key, "i");//不区分大小写
        condition = {
            $or: [
                { title: { $regex: exp } }, //文章标题
                { content: { $regex: exp } },//文章描述
      
            ]
        }
    }
    const page = parseInt(req.query.page);
    const limit = parseInt(req.query.limit);
    const data = await db.Article.find(condition).skip((page - 1) * limit).limit(limit).sort(value);
    const count = await db.Article.count(condition);
    res.send({
        code: 0,
        message: "",
        count,
        data
    });
})



//得到单个文章
router.get("/:id", async (req, res) => {
    const data = await db.Article.findById(req.params.id)
    res.send({
        "code": 0,
        "message": "",
        data
    });
})
module.exports = router;

